<?php
namespace Index\Controller;
use Think\Controller;
use Org\Util\Wechat;
header("Content-type: text/html; charset=utf-8"); 
class ResearchController extends Controller {
    public $wx = null; 
    
    public function _initialize(){  
        $this->wx = new Wechat(C('options'));
    }
    //精彩活动页面
    public function index(){//exit('@@@');
        $openid = session('openid');
        if(empty($openid)){
            $this->redirect('wlg');
        }
		$user=M('customer')->where('openid="'.$openid.'"')->find();
		$status=$user['status_customer'];

        $list=M('research')->where('state=1')->find();
        
        $preg ="/<img src=\"(.+?)\".*?>/";//只能有src     
        preg_match_all($preg,html_entity_decode($list['img']),$arr);
        $array=$arr[1][0]; 
        //print_r($array);exit('!@$');
        //调用微信jssdk获取签名等
        $weObj = new \Org\Util\Wechat(C('options'));
        //获取签名
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $sign = $weObj->getJsSign($url);
        $this->assign('status',$status);
        $this->assign('sign',$sing);
        $this->assign('list',$list);
        $this->assign('img',$array);
        $this->assign('res',$openid);
        $this->display('index');
    }

    public function wlg(){ 
        $callback = 'http://sunwayuchoice.com/index.php/Research/lgback';
        $url = $this->wx->getOauthRedirect($callback);
        header('location:'.$url);
    }
    
    public function lgback(){ 
        $tk = $this->wx->getOauthAccessToken();
        session('openid',$tk['openid']);
        $this->redirect('index');
    }
    

    //发放优惠券
    public function send(){
        $openid=session('openid');
      /*  if (empty($openid)) {
            error('用户openid不存在',$_SERVER['HTTP_REFERER']);
        }*/
        //查找用户名字
        $name_f=M('customer')->where('openid="'.$openid.'"')->find();
        $name=$name_f['name'];
        //查找开启的问卷调查
        $list=M('research')->where('state=1')->find();
        //查出对应的奖品
        $aid=unserialize($list['aid']);
        foreach ($aid as $key => $value) {
            $da[]=M('award')->where('id="'.$value.'"')->find();
            $data=$da;
        }

        //概率
        $gai=rand(0,100);
        foreach ($data as $k => $v) {
           $percent=$v['percent'];
          
           if ($gai<$percent) {
              $q_names[]=$v['name'];
              $array=$q_names;
           }
        } 
        $count=count($array);
        $arr=rand(0,$count-1);
        $q_name=$array[$arr];
        if (!empty($q_name)) {
            //开启事物
            M()->startTrans();
            $res_f=M('award')->where('name="'.$q_name.'"')->find();
            $balance=$res_f['balance']+1;
            if ($balance>=$res_f['num']) {
                error('优惠券已经被抢光，感谢参与',"http://sunwayuchoice.com/index.php/Enter/index");
            }
            $data=array(
                'balance'=>$balance,
                );
            $res_save=M('award')->where('name="'.$q_name.'"')->data($data)->save();
            if(false==$res_save){
                error('领取优惠券失败',"http://sunwayuchoice.com/index.php/Enter/index");
            }
             //劵码
            $code=$this->random();
            //插入获奖名单
            $d=array(
                'name'=>$name,
                'ctime'=>time(),
                'q_name'=>$q_name,
                'q_ma'=>$code,
                'openid'=>$openid,
                );
            $res_add=M('winner')->data($d)->add();
            if (false==$res_add) {
                error('领取优惠券失败，请联系客服人员',"http://sunwayuchoice.com/index.php/Enter/index");
            }
            if(false!==$res_save && false!==$res_add){
                M()->commit();
                
                $weObj = new Wechat(C('options'));  
				$data =  array(
					"touser" =>	$openid,
					"template_id" =>	"Yu4ci-e8xVZ90dVZ1WwcUm0gJSCyy_rE0XXZ4Mc8feY",
					"url" =>	"http://sunwayuchoice.com/index.php/Gj/coupon_list",
					"topcolor" =>	"#FF0000",
					"data" => array( 
							'first'	=>	array(
								"value" =>	"您有一张新的优惠券",
								"color" =>	"#ff0000"
							),
							'keyword1'	=>	array(
								"value" =>	'优惠券名称："'.$q_name.'"',
								"color" =>	"#173177"
							),
							'keyword2'	=>	array(
								"value" =>	'优惠券到账通知',
								"color" =>	"#173177"
							),
							'keyword3'	=>	array(
								"value" =>	"您好，请您到个人中心查看优惠券",
								"color" =>	"#173177"
							),
							'remark'	=>	array(
								"value" =>	"尚元优家Uchoice",
								"color" =>	"#173177"
							)
						)
				);
				$st = $weObj->sendTemplateMessage($data);
                
                
                
                
                error('亲,恭喜获得"'.$q_name.'"优惠券,请到个人中心查看',"http://sunwayuchoice.com/index.php/Enter/index");
            }else{
                M()->rollback();
            }
        }else{ 
             error('抱歉，亲，您没有获得优惠券，再接再厉',"http://sunwayuchoice.com/index.php/Enter/index");
        }
      
    }

    //生成劵码
    public function random($length=8, $type='string', $convert=0){
        $config = array(
            'number'=>'1234567890',
            'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );
        
        if(!isset($config[$type])) $type = 'string';
        $string = $config[$type];
        
        $code = '';
        $strlen = strlen($string) -1;
        for($i = 0; $i < $length; $i++){
            $code .= $string{mt_rand(0, $strlen)};
        }
        if(!empty($convert)){
            $code = ($convert > 0)? strtoupper($code) : strtolower($code);
        }
        return $code;
    }
    //问卷调查问题
    public function question(){
        //查找开启的问卷调查
        $list=M('research')->where('state=1')->find();
        
        $openid=session('openid');
        
      /*  if($res['access']==1){
			$list_user=M('customer')->where('openid="'.$openid.'"')->find();
			if($list_user['status_customer']!=1){
				 error('尊敬的用户您好，本次问卷调查只有非VIP用户可以参加，感谢您的参与','http://sunwayuchoice.com/index.php/Gj/index');
			}
		}
        
        if($res['access']==2){
			$list_user=M('customer')->where('openid="'.$openid.'"')->find();
			if($list_user['status_customer']!=2){
				 error('尊敬的用户您好，本次问卷调查只有VIP用户可以参加，感谢您的参与','http://sunwayuchoice.com/index.php/Gj/index');
			}
		}*/
        
        
        
        
        //查找属于问卷调查的问题
        $id=$list['id'];//exit('@');
        //问题
        $list_question=M('question')->where('rid="'.$id.'"')->select();
        //问题的数量
        $count=M('question')->where('rid="'.$id.'"')->count();
        foreach ($list_question as $key => $value) {
            $name[]=unserialize($value['checkbox']);
            $array=$name;
        }
        $arr=array('list'=>$list_question,'arr'=>$array,'count'=>$count);
        //print_r($arr);exit;
        $this->assign('list',$arr);
        $this->display('quest');
    }


    public function an(){
        //接收答案
        $arr=I("arr");
       // print_r($arr);exit;
        $res=M('research')->where('state=1')->find();
        
     
        
        
        
        $r_name=$res['name'];
        $openid=session('openid');
        
        
    
        
        //判断是否是管理员
		$list_manager=M('rbac_manager')->where('openid="'.$openid.'"')->find();
		if(!empty($list_manager)){
			 error('尊敬的管理员您好，本系统暂时不支持客服答题，感谢参与','http://sunwayuchoice.com/index.php/Gj/index');
		}
        
        if (empty($openid)) {
           error('用户openid不存在',$_SERVER['HTTP_REFERER']);
        }
       
        //同一个问卷调查只能回答一次
		$check_an=M('answer')->where('openid="'.$openid.'"')->select();
		
		
		foreach($check_an as $key=>$value){
			$name=$value['r_name'];
			if($r_name==$name){
		    error('尊敬的用户您好，同一个问卷调查只能回答一次，感谢您的参与','http://sunwayuchoice.com/index.php/Gj/index');
		  }
			
		}
			
        $list=M('customer')->where('openid="'.$openid.'"')->find();
        $name=$list['name'];
        $phone=$list['phone'];
        $data=array(
            'r_name'=>$r_name,
            'name'=>$name,
            'phone'=>$phone,
            'answer'=>$arr,
            'openid'=>session('openid'),
            'ctime'=>time(),
            );
        //print_r($data);exit('@@@');
        $res_add=M('answer')->data($data)->add();
        if (false!==$res_add) {
            $this->send();
        }
    }
}


?>